package section

import (
	"context"
	// "fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateSectionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateSectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateSectionLogic {
	return &UpdateSectionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateSectionLogic) UpdateSection(in *backend.SectionInfo) (*backend.BaseResp, error) {
	// logrus.Info(fmt.Sprintf("UpdateSection: %+v", in.NewMedia))

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 && in.Status != nil { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				section, err := l.svcCtx.Section.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				section.Status = uint8(*in.Status)
				section.UpdatedAt = now
				err = l.svcCtx.Section.Update(l.ctx, tx, section, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &backend.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	section, err := l.svcCtx.Section.FindOneNoCache(l.ctx, tx, *in.Id)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}

	mediaUidMap := make(map[uint64]*model.AttachmentRelationship)
	if !skipMedia { // 查询媒体关联表获取原有数据
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": {section.ID},
		}
		filterMap[model.AttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": {globalkey.AttachmentLogTypeSection},
		}
		list, _, err := l.svcCtx.Section.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.RelationshipID] = v
			}
		}
	}

	if in.Type != nil {
		section.Type = uint8(*in.Type)
	}
	if in.Title != nil {
		section.Title = strings.TrimSpace(*in.Title)
	}
	if in.Subtitle != nil {
		section.Subtitle = strings.TrimSpace(*in.Subtitle)
	}
	if in.PicId != nil && *in.PicId > 0 {
		section.PicID = *in.PicId
	}
	if in.PicUrl != nil {
		section.PicURL = strings.TrimSpace(*in.PicUrl)
	}
	if in.Status != nil {
		section.Status = uint8(*in.Status)
	}
	if in.Sort != nil {
		section.Sort = uint16(*in.Sort)
	}
	section.UpdatedAt = time.Now()
	if in.StartedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
			section.StartedAt = null.TimeFrom(localTime)
		}
	}
	if in.EndedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
			section.EndedAt = null.TimeFrom(localTime.Add(time.Minute * -1))
		}
	}

	existThumbMap := make(map[string]uint64) // 在封面图中存在
	rel := &model.SectionRel{}
	if !skipMedia && len(in.NewMedia) > 0 {
		var thumbnailOrder uint
		var thumbnailId uint64
		var thumbnailUrl string
		for idx, v := range in.NewMedia {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			if len(url) == 0 {
				continue
			}

			var thumbnail uint8
			if v.Thumbnail != nil && *v.Thumbnail > 0 {
				thumbnail = uint8(*v.Thumbnail)
			}
			var order uint
			if v.Order != nil {
				order = uint(*v.Order)
			} else {
				order = uint(idx) + globalkey.AttachmentOrderOffset
			}
			var altText string
			if v.AltText != nil && len(*v.AltText) > 0 {
				altText = *v.AltText
			}

			var meta []string
			if v.Name != nil && len(*v.Name) > 0 {
				meta = append(meta, "filename:"+*v.Name)
				if len(altText) == 0 {
					altText = *v.Name
				}
			}
			if v.MetaData != nil && len(*v.MetaData) > 0 {
				meta = append(meta, *v.MetaData)
			}
			if v.MimeType != nil && len(*v.MimeType) > 0 {
				meta = append(meta, "mimeType:"+*v.MimeType)
			}
			metaData := strings.Join(meta, ";")

			var mediaId uint64
			if v.Id != nil && len(*v.Id) > 0 {
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
					mediaId = uint64(i)
				}
			}

			var uid uint64
			if v.Uid != nil && *v.Uid > 0 {
				uid = *v.Uid
			}
			if uid > 0 { // 旧有
				if _, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
					delete(mediaUidMap, uid)
					rel.Media = append(rel.Media, &model.AttachmentRelationship{
						RelationshipID:      uid,
						AttachmentID:        mediaId,
						AttachmentThumbnail: thumbnail,
						AttachmentOrder:     order,
						AttachmentImageURL:  url,
						AttachmentImageAlt:  altText,
						AttachmentImageMeta: metaData,
					})

					if thumbnail > 0 {
						existThumbMap[url] = mediaId
					}
				}

				continue
			}

			rel.Media = append(rel.Media, &model.AttachmentRelationship{
				AttachmentID:        mediaId,
				AttachmentThumbnail: thumbnail,
				AttachmentOrder:     order,
				AttachmentImageURL:  url,
				AttachmentImageAlt:  altText,
				AttachmentImageMeta: metaData,
			})

			if thumbnail > 0 {
				existThumbMap[url] = mediaId
			}
		}

		for _, v := range rel.Media {
			if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
				thumbnailOrder = v.AttachmentOrder
				thumbnailId = v.AttachmentID
				thumbnailUrl = v.AttachmentImageURL
			}
		}

		if len(section.PicURL) == 0 {
			section.PicID = thumbnailId
			section.PicURL = thumbnailUrl
		}
	}

	if !skipMedia {
		for _, v := range mediaUidMap {
			if v.AttachmentThumbnail > 0 {
				if _, ok := existThumbMap[v.AttachmentImageURL]; ok { // 如果在封面中，保留一次
					delete(existThumbMap, v.AttachmentImageURL)
					continue
				}
			}

			rel.DelMediaIds = append(rel.DelMediaIds, v.RelationshipID)
		}
	}

	err = l.svcCtx.Section.Update(l.ctx, tx, section, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &backend.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
